<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2022/9/26
 * Time: 5:37 PM
 */

namespace app\aso;

use app\common\lib\exception\ApiException;
use think\Controller;
use think\Request;

class Auth extends Controller
{
    /**
     * @throws ApiException
     */
    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $param = $this->request->only(['channelid', 'idfa', 'os', 'ip', 'apptype', 'keyword', 'time']);

        if (empty($param['idfa']) || empty($param['os']) || empty($param['ip']) || empty($param['apptype']) || empty($param['keyword']) || empty($param['time']))
        {
            throw new ApiException('Request Error, Please try again later', 200, 0);
        }

        if (strlen($param['idfa']) < 32)
        {
            throw new ApiException('Invalid idfa');
        }

        $signTmp = $param['keyword'];
        unset($param['keyword']);
        $strSalt = '58b4e20e71bbe129';
        $sign = $this->getSign($param, $strSalt);
        if ($sign !== $signTmp)
        {
            throw new ApiException('Invalid Sign.', 200, 1);
        }
    }

    //进行签名
    public function getSign($Obj, $apiKey)
    {
        foreach ($Obj as $k => $v)
        {
            $Parameters[strtolower($k)] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $apiKey;
        //签名步骤三：MD5加密
        return strtoupper(md5($String));
    }

    //将数组转成uri字符串
    protected function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        $reqPar = '';
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if ($urlencode)
            {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
}
